package com.example.sunmiv1.base;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;


import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.ClassificationBean;
import com.example.sunmiv1.listener.LoadMoreOnScrollListener;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public abstract class BaseChooseActivity extends BaseActivity {
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.tv_pick_sort)
    TextView tvPickSort;
    @BindView(R.id.ed_num_search)
    EditText edNumSearch;
    @BindView(R.id.iv_search_code)
    ImageView ivSearchCode;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;
    @BindView(R.id.btn_checkall)
    Button btnCheckall;
    @BindView(R.id.btn_checkall_not)
    Button btnCheckallNot;
    @BindView(R.id.btn_add_to_list)
    Button btnAddToList;
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.rv_goods_choose)
    RecyclerView rvGoodsChoose;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    protected static final int GET_CATEGORY_INFO = 0x0001;
    protected static final int GET_GOODS_STORE_RETREAT_INFO = 0x0010;
    protected static final int GET_OTHER_GOODS_STORE_RETREAT_INFO = 0x0011;
    protected static final int GET_ERROR_STATUS = 0x1000;

    protected ACache aCache;// 緩存
    protected String userType;// 用戶身份

    protected ClassificationBean classificationBean;
    protected List<String> options1Items;
    protected List<List<String>> options2Items;
    protected List<List<List<String>>> options3Items;
    protected String[] category = {"", "", ""}; // 三級分類的對應的id


    protected String supplierId;
    protected String warehouseId;
    protected ArrayList<String> notInIdArr;//  已選中的貨物id列表（選中傳回上頁，可從上頁跳轉到此頁的時候返回此列表  添加和選擇頁面都要維護這個列表 ）
    protected int page;
    protected boolean loadOver;
    protected String limit;
    protected LoadingDialog loadingDialog;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_purchase_refund_goods_choose);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.baseChooseTitle);
        loadingDialog = new LoadingDialog(this);
        aCache = ACache.get(this);
        LogUtil.i("觸發initView()");

    }

    @Override
    protected void initData() {
        initChoiceList();
        notInIdArr = new ArrayList<>();
        userType = aCache.getAsString("userType");
        options1Items = new ArrayList<>();
        options2Items = new ArrayList<>();
        options3Items = new ArrayList<>();
        Intent intent = getIntent();
        warehouseId = intent.getStringExtra("WarehouseId");
        supplierId = intent.getStringExtra("SupplierId");
        notInIdArr.addAll(intent.getStringArrayListExtra("not_in_ids"));
        LogUtil.i("BaseChooseActivity.notInIdArr:" + notInIdArr.size());
        page = 1;
        loadOver = false;
        limit = "20";
        getCategoryInfo();
        getListInfo(page);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rvGoodsChoose.setLayoutManager(linearLayoutManager);
        setAdapter();
        rvGoodsChoose.addOnScrollListener(new LoadMoreOnScrollListener(linearLayoutManager) {
            @Override
            public void onLoadMore(int currentPage) {
                if (currentPage > page) {
                    LogUtil.e("currentPage:" + currentPage);
                    progressBar.setVisibility(View.VISIBLE);
                    getListInfo(++page);
                }
            }
        });
    }

    /*  初始化  列表*/
    protected abstract void initChoiceList();

    /*  初始化  或   刷新  Adapter*/
    protected abstract void setAdapter();

    /*  網絡加載  */
    protected abstract void getListInfo(int page);


    @Override
    protected void initListener() {
    }

    /**
     * 獲取選擇器返回值的回調方法
     *
     * @param tvShowText tv需要顯示的字符串
     */
    public void getInfo(String tvShowText) {
    }

    /*
        打包頁面傳參（含有實現Serializable的bean），並返回
     *  未將list中的checked狀態置爲false
     */
    /*public <T extends Parcelable> void putExtra(Context thisContext, Class thatContext, ArrayList<T> choiceList) {
        if (choiceList.size() != 0) {
            Intent intent = new Intent(thisContext, thatContext);
            intent.putStringArrayListExtra("choice_list", choiceList);
            intent.putExtra("supplier_id", supplierId);
            intent.putExtra("warehouse_id", warehouseId);
            setResult(RESULT_OK, intent);
        }
        finish();
    }*/

    /**
     * 重載方法，可適配實現Serializable的bean
     *
     * @param thisContext 此activity
     * @param thatContext 跳轉至activity
     * @param choiceList  選中的列表
     * @param s           （隨意增加的參數，傳空字符串即可）
     * @param <T>         任意實現Serializable接口的bean
     */
    public <T extends Serializable> void putExtra(Context thisContext, Class thatContext, ArrayList<T> choiceList, String s) {
        if (choiceList.size() != 0) {
            Intent intent = new Intent(thisContext, thatContext);
            intent.putExtra("choice_list", choiceList);
            intent.putExtra("supplier_id", supplierId);
            intent.putExtra("warehouse_id", warehouseId);
            setResult(RESULT_OK, intent);
        }
        finish();
    }

    /* 彈出選擇器  三級列表封裝*/
    public void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            //返回的分別是三個級別的選中位置
            String opt1tx, opt2tx, opt3tx;
            Arrays.fill(category, "");
            opt1tx = options1Items.size() > 0 ?
                    options1Items.get(options1) : "";
            category[0] = options1Items.size() > 0 ? classificationBean.getGoodscate().get(options1).getId() : "";

            opt2tx = options2Items.get(options1).get(options2);
            if (classificationBean.getGoodscate().size() > 0
                    && classificationBean.getGoodscate().get(options1).getChild().size() > 0)
                category[1] = classificationBean.getGoodscate().get(options1).getChild().get(options2).getId() == null ? "" : classificationBean.getGoodscate().get(options1).getChild().get(options2).getId();

            opt3tx = options3Items.get(options1).get(options2).get(options3);
            if (classificationBean.getGoodscate().size() > 0
                    && classificationBean.getGoodscate().get(options1).getChild().size() > 0
                    && classificationBean.getGoodscate().get(options1).getChild().get(options2).getChild().size() > 0)
                category[2] = classificationBean.getGoodscate().get(options1).getChild().get(options2).getChild().get(options3).getId() == null ? "" : classificationBean.getGoodscate().get(options1).getChild().get(options2).getChild().get(options3).getId();

            opt1tx = opt1tx.length() > 3 ? opt1tx.substring(0, 3) + ".." : opt1tx;
            opt2tx = opt2tx.length() > 3 ? opt2tx.substring(0, 3) + ".." : opt2tx;
            opt3tx = opt3tx.length() > 3 ? opt3tx.substring(0, 3) + ".." : opt3tx;
            LogUtil.i("opt1tx:" + opt1tx + "opt2tx:" + opt2tx + "opt3tx:" + opt3tx);

            String tx = opt1tx;
            if (!opt2tx.isEmpty()) {
                tx = opt1tx + ">" + opt2tx;
            }
            if (!opt3tx.isEmpty()) {
                tx = opt1tx + ">" + opt2tx + ">" + opt3tx;
            }
            getInfo(tx);
        })
                .setTitleText("")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //設置選中項文字顏色
                .setContentTextSize(14)
                .build();
        /*pvOptions.setPicker(options1Items);//一級選擇器*/
//        pvOptions.setPicker(options1Items, options2Items);//二級選擇器
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三級選擇器
        pvOptions.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.REQ_QR_CODE:
                    Bundle bundle = data.getExtras();
                    edNumSearch.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    getListInfo(1);
                    break;
            }
        }
    }

    /* 獲得分類信息*/
    protected void getCategoryInfo() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("store_id", aCache.getAsString("storeid"));
            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
//            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }else{
                jsonObject.put("operator_id",aCache.getAsString("operator_id"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, Common.ADD_CLASSIFICATION, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                classificationBean = GsonUtils.JsonToBean(text, ClassificationBean.class);
                if (classificationBean.getStatus() == 1) {
                    List<ClassificationBean.GoodscateBean> goodscateBeans = new ArrayList<>(classificationBean.getGoodscate());
                    List<ClassificationBean.GoodscateBean.ChildBeanX> childBeanXES;
                    List<String> option2ChildItem;
                    for (ClassificationBean.GoodscateBean goodscateBean : goodscateBeans) {
                        options1Items.add(goodscateBean.getClass_name());
                        childBeanXES = new ArrayList<>(goodscateBean.getChild());
                        List<List<String>> option3CItem = new ArrayList<>();
                        option2ChildItem = new ArrayList<>();
                        if (goodscateBean.getHaschild() == 1) {
                            for (ClassificationBean.GoodscateBean.ChildBeanX childBeanX : childBeanXES) {
                                option2ChildItem.add(childBeanX.getClass_name());
                                List<String> option3CCItem = new ArrayList<>();
                                if (childBeanX.getHaschild() == 1)
                                    for (ClassificationBean.GoodscateBean.ChildBeanX.ChildBean childBean : childBeanX.getChild()) {
                                        option3CCItem.add(childBean.getClass_name());
                                    }
                                else {
                                    option3CCItem.add("");
                                }
                                option3CItem.add(option3CCItem);
                            }
                        } else {
                            option2ChildItem.add("");
                            List<String> option3CCItem = new ArrayList<>();
                            option3CCItem.add("");
                            option3CItem.add(option3CCItem);
                        }

                        options2Items.add(option2ChildItem);
                        options3Items.add(option3CItem);
                    }
                    loadingDialog.dismiss();
                } else {// status
                    loadingDialog.dismiss();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * @param notInIdArr 添加和選擇頁面維護的不需要搜索的貨物id
     * @return 搜索需要用的notInIds字符串
     */
    protected String toNotInIds(ArrayList<String> notInIdArr) {
        if (notInIdArr.isEmpty()) {
            return "";
        } else {
            StringBuilder notInIds = new StringBuilder();
            if (notInIdArr.size() > 0)
                notInIds.append(notInIdArr.get(0));
            if (notInIdArr.size() > 1) {
                for (int i = 1; i < notInIdArr.size(); i++) {
                    notInIds.append("," + notInIdArr.get(i));
                }
            }
            return notInIds.toString();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
